import pandas as pd
import numpy as np
import joblib
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

from sklearn.metrics import classification_report , roc_auc_score

def logistic_regression():
    """
    逻辑回归进行癌症预测
    :return: None
    """
    # 1.读取数据
    column_name = ['Sample code number', 'Clump Thickness', 'Uniformity of Cell Size', 'Uniformity of Cell Shape',
                   'Marginal Adhesion', 'Single Epithelial Cell Size', 'Bare Nuclei', 'Bland Chromatin',
                   'Normal Nucleoli', 'Mitoses', 'Class']
    data = pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data",
    names=column_name)
    # 2. 缺失值处理
    data = data.replace(to_replace='?', value=np.nan) # 替换缺失值
    data.dropna(inplace=True) # 删除缺失样本
    # 3.取出特征值
    # 3.1 筛选特征值与目标值
    x = data.iloc[:,1:-1]
    y = data["class"]
    # 分割数据集
    x_train, x_test, y_train, y_test = train_test_split(x, y)
    # 4.特征工程
    # 4.1 进行标准化
    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test = transfer.transform(x_test)
    # 5.预估器流程
    # 使用逻辑回归
    estimator = LogisticRegression()
    estimator.fit(x_train, y_train)
    print("得出来的权重：", estimator.coef_)
    # 预测类别
    print("预测的类别：", estimator.predict(x_test))
    # 得出准确率
    print("预测的准确率:", estimator.score(x_test, y_test))

    # # 5.1 保存模型
    # joblib.dump(estimator, "my_ridge.pkl")
    # # 5.2 加载模型
    # estimator = joblib.load("my_ridge.pkl")

    # 6.查看精确率、召回率、F1-score
    y_predict = estimator.predict(x_test)
    report = classification_report(y_test, y_predict, labels=[2,4], target_names=["良性","恶性"])
    print("精确率、召回率、F1-score：\n", report)

    # 7.AUC指标
    # 将 y_test 转换成0,1
    y_true = np.where(y_test > 3, 1, 0)
    auc = roc_auc_score(y_true, y_predict)
    print("auc 指标：\n", auc)


    return None

if __name__ == "__main__":
    logistic_regression()